package com.pine.dbant.core.service.impl;

import com.github.sd4324530.jtuple.Tuple2;
import com.pine.dbant.common.plugin.DatabasePlugin;
import com.pine.dbant.common.plugin.PluginFactory;
import com.pine.dbant.common.plugin.meta.JdbcMetaAnalysisException;
import com.pine.dbant.common.plugin.meta.MetadataAnalysis;
import com.pine.dbant.common.plugin.meta.QueryMetadataParam;
import com.pine.dbant.core.entity.Connection;
import com.pine.dbant.core.model.dto.FunctionParamDTO;
import com.pine.dbant.core.service.BasePluginService;
import com.pine.dbant.core.service.ConnectionService;
import com.pine.dbant.core.service.MetadataService;
import com.pine.sunflower.core.plugin.Configuration;
import com.pine.sunflower.core.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xiaoyuan
 * @create 2022/11/30 9:48
 **/
@Service
public class MetadataServiceImpl extends BasePluginService implements MetadataService {

    @Autowired
    private ConnectionService connectionService;
    @Autowired
    private PluginFactory pluginFactory;


    @Override
    public Object executeFunction(FunctionParamDTO functionParamDTO) {
        Object connId =  functionParamDTO.getParams().get("connId");
        if(connId==null){
            throw new JdbcMetaAnalysisException("连接id不能为空");
        }
        Tuple2<Connection,DatabasePlugin> databasePluginTuple2  = buildDatabasePlugin(functionParamDTO.getPluginId(),Long.valueOf(String.valueOf(connId)));
        MetadataAnalysis metadataAnalysis = databasePluginTuple2.second.createMetadataAnalysis(databasePluginTuple2.first);
        QueryMetadataParam queryMetadataParam = new QueryMetadataParam();
        queryMetadataParam.setType(functionParamDTO.getType());
        queryMetadataParam.setConfiguration(functionParamDTO.getParams()==null?Configuration.from("{}"):
                Configuration.from(JsonUtils.toString(functionParamDTO.getParams())));
        return metadataAnalysis.queryMetadata(queryMetadataParam);
    }


}
